-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local skynet = require 'skynet'
local log = require 'mc.logging'
local context = require 'mc.context'
local signal = require 'mc.signal'
local cmn = require 'common'

local cpld_test_obj = {}

function cpld_test_obj.init(fw)
    cpld_test_obj.logic_fw = fw or {}
    cpld_test_obj.signal = signal.new()
    return cpld_test_obj
end

function cpld_test_obj:add_cpld_test_object(object, fw)
    if not fw.test_object then
        fw.test_object = {}
    end
    fw.test_object[#fw.test_object + 1] = object
end

function cpld_test_obj:add_cpld_test(object)
    local retry_times = 10
    for i = 1, retry_times do
        for _, v in ipairs(cpld_test_obj.logic_fw) do
            v.test_chip_nums = 0
            local refname = string.format('%s', object.RefLogicFirmware)
            if v.csr.name == refname then
                cpld_test_obj:add_cpld_test_object(object, v)
                return
            end
        end
        skynet.sleep(500)
    end
    log:error('test obj %s not found ref logic fw.', object.name)
    return
end

function cpld_test_obj:on_add_test_obj(class_name, object, position)
    local switch = {
        ['CpldSpaceTest'] = function()
            cmn.skynet.fork(function()
                cpld_test_obj:add_cpld_test(object)
                cpld_test_obj.signal:emit()
            end)
        end
    }

    if switch[class_name] then
        switch[class_name]()
        log:notice('[cpld_test] Add object, class: %s, position: %s', class_name, position)
    end
end

return cpld_test_obj
